﻿<?xml version="1.0" encoding="UTF-8" ?>
<Module xmlns="http://www.opensocial.org">
    <ModulePrefs title="Google Contacts Gadget">
        <Require feature="dynamic-height"/>
        <Require feature="opensocial-0.8"/>
        <OAuth>
            <Service name="gmail">
                <Request
                  url="https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/"
                  method="GET" />
                
                <Access
                  url="https://www.google.com/accounts/OAuthGetAccessToken"
                  method="GET" />
                
                <Authorization
                  url="https://www.google.com/accounts/OAuthAuthorizeToken" />
            </Service>
        </OAuth>
    </ModulePrefs>
    <Content type="html">
        <![CDATA[
    <link rel="stylesheet" type="text/css" href="/content/main.css" />

    <div id="loading">
    <img src="/content/images/loader.gif" /> Initializing gadget ...
    </div>
    <div id="main" style="display: none">
    </div>

    <div id="approval" style="display: none">
      <img src="/content/images/add.png" />
      <a id="personalize"
        onclick="javascript:showOneSection('waiting'); return true;" target="approve" >Get my Google contacts</a>
    </div>

    <div id="waiting" style="display: none">
      Please click <a href="javascript:void(0);" onclick="javascript:showLoading('Fetching data ...');fetchData();">here</a>
      once you've approved access to your data.
    </div>
    <script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript" ></script>
    <script type="text/javascript">
        var baseurl;
        function init() {
            var urlparams = gadgets.util.getUrlParameters();
            baseurl = urlparams["parent"];
            fetchData();
        }
        
        function showLoading(content) {
            $('#loading').html("<img src=\"" + baseurl + "/content/images/loader.gif\" /> " + content);
            showOneSection('loading');
        }
        
        function showOneSection(toshow)
        {
        var sections = [ 'main', 'approval', 'waiting', 'loading' ];
        for (var i=0; i < sections.length; ++i) {
          var s = sections[i];
          var el = document.getElementById(s);
          if (s === toshow) {
            el.style.display = "block";
          } else {
            el.style.display = "none";
          }
        }
      }

      function showResults(result) {
        showOneSection('main');
        $("#main").append("<b>" + result.feed.title.$t + "</b>")
                    .append("<br/>")
                    .append("Select contacts that you want to add:");
        
        list = result.feed.entry;
        for(var i = 0; i < list.length; i++) 
        {
          entry = list[i];
          $("#main").append("<div>")
                    .append("<input type='checkbox' checked='checked' />")
                    .append("<span id='name'>" + entry.title.$t + "</span>")
                    .append(', ')
                    .append("<span id='email'>" + entry.gd$email[0].address + "</span>")
                    .append("</div>");
      }
        $("#main").append("<div class='pad4'>")
                    .append("<button onclick='send_invitation();'>Send invitations</button>")
                    .append("</div>");
        gadgets.window.adjustHeight();
      }

      function send_invitation() {
            var names = $('input:checked').siblings("#name");
            var emails = $('input:checked').siblings("#email");
            var data = [];
            for (var i = 0; i < emails.length; i++) {
                data.push($(names[i]).text() + "," + $(emails[i]).text());
            }
            var params = {};
        
        var url = baseurl + "/contacts/invite";
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
        params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.NONE;
        params[gadgets.io.RequestParameters.POST_DATA] = "data=" + gadgets.json.stringify(data);
        params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
        gadgets.io.makeRequest(url, function(response) {
            alert(response.error + "," + response.data);
            if (response.error != undefined || response.data != "OK") {
                $("#main").html("Error: " + response.error.join(','));
            }
            else {
                $("#main").html("Invitations have been sent out");
            }
            showOneSection('main');
        }, params);
        
        showLoading('Sending invitations ...');
      }

      function fetchData() {
        var params = {};
        var url = "http://www.google.com/m8/feeds/contacts/default/base?alt=json";
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
        params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "gmail";
        params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;

        gadgets.io.makeRequest(url, function (response) {
          if (response.oauthApprovalUrl) {
            $('#personalize').attr('href', response.oauthApprovalUrl);
            showOneSection('approval');
          } else if (response.data) {
            showOneSection('main');
            showResults(response.data);
          } else {
	    errorStr = response.oauthErrorText;
            $('#main').append('Something went wrong: ' + errorStr);
            showOneSection('main');
          }
        }, params);
      }

      gadgets.util.registerOnLoadHandler(init);
    </script>
        ]]>
    </Content>
</Module>
